package com.woniu.controller;

import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.annotation.OperateLog;
import com.woniu.entity.AllUser;
import com.woniu.mapper.AllUserMapper;
import com.woniu.service.AllUserService;
import com.woniu.util.ResponseData;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.util.Date;

/**
 * @Description 用户表控制器
 * @Param
 * @Return
 * @Author pml
 * @Date 2025/6/11 20:10
 */

@RestController
@RequestMapping("alluser")
public class AllUserController {
    @Autowired
    private SmsController smsController;

    @Resource
    private AllUserMapper allUserMapper;
    /**
     * 注入Service而非直接注入Mapper，符合分层架构
     * Controller层只处理HTTP请求和响应，不包含业务逻辑
     */
    @Resource
    private AllUserService allUserService;

    /**
     * @Description 添加用户
     * @param allUser 用户信息
     * @return 操作结果
     * @Author pml
     * @Date 2025/6/11 20:10
     */
    @PostMapping("/add")
    public SaResult add(@RequestBody AllUser allUser) {
        allUser.setCreateTime(new Date());
        // 可根据实际需求设置 isDelete 等默认值，比如初始为未删除状态
        allUser .setIsDelete("0");
//        return SaResult.ok().setData(allUserMapper.insert(allUser));
        return SaResult.ok().setData(allUserService.save(allUser));
    }
    /**
     * @Description 删除用户
     * @param id 用户ID
     * @return 操作结果
     * @Author pml
     * @Date 2025/6/11 20:10
     */
    @DeleteMapping("/delete/{id}")
    public SaResult delete(@PathVariable Integer id) {
//        return SaResult.ok().setData(allUserMapper.deleteById(id));
        return SaResult.ok().setData(allUserService.removeById(id));
    }
    /**
     * @Description 修改用户
     * @param allUser 用户信息
     * @return 操作结果
     * @Author pml
     * @Date 2025/6/11 20:10
     */
    @PutMapping("/update")
    public SaResult update(@RequestBody AllUser allUser) {
//        return SaResult.ok().setData(allUserMapper.updateById(allUser));
        return SaResult.ok().setData(allUserService.updateById(allUser));
    }
    /**
     * @Description 根据id查询用户
     * @param id 用户ID
     * @return 用户信息
     * @Author pml
     * @Date 2025/6/11 20:10
     */
    @GetMapping("/get/{id}")
    public SaResult getById(@PathVariable Integer id) {
//        return SaResult.ok().setData(allUserMapper.selectById(id));
        return SaResult.ok().setData(allUserService.getById(id));
    }
//    用户头像上传
@PostMapping("/uploadAvatar/{id}")
public SaResult uploadAvatar(@PathVariable Integer id, @RequestPart("file") FilePart filePart) {
    // 调用服务层处理上传逻辑
    String avatarUrl = allUserService.uploadAvatar(id, filePart);
    if (avatarUrl != null) {
        allUserMapper.update(new UpdateWrapper<AllUser>().set("avatar_url", avatarUrl).eq("user_id", id));
    }
    return SaResult.ok().setData(avatarUrl);
}

    /**
     * @Description 查询所有用户
     * @Param []
     * @return 用户列表
     * @Author pml
     * @Date 2025/6/11 20:10
     */
    @OperateLog(module = "user", operateType = "query", content = "查询所有用户列表")
    @GetMapping("/list")
    public Mono<SaResult> list(@RequestHeader("Authorization") String token)  {
        System.out.println("查询所有用户列表 - 操作人token: " + token);
//        return SaResult.ok().setData(allUserMapper.selectList(null));
//        return SaResult.ok().setData(allUserService.list());
        return Mono.just(SaResult.ok().setData(allUserService.list()))
                .subscribeOn(Schedulers.boundedElastic());
    }
    /**
     * @Description 搜索用户
     * @param keyword 搜索关键词
     * @return 搜索结果
     * @Author pml
     * @Date 2025/6/11 20:10
     */
    @GetMapping("/search")
    public SaResult search(@RequestParam String keyword) {
//        QueryWrapper<AllUser> wrapper = new QueryWrapper<>();
//        wrapper.like("user_name", keyword)      // 用户名
//                .or().like("nickname", keyword)   // 昵称
//                .or().like("contact", keyword)    // 联系电话
//                .or().like("creator", keyword);   // 新增：创建人（如 'register' 或用户名）
//        return SaResult.ok().setData(allUserMapper.selectList(wrapper));
        QueryWrapper<AllUser> wrapper = allUserService.createSearchQueryWrapper(keyword);
        return SaResult.ok().setData(allUserService.list(wrapper));
    }

    /**
     * @Description 获取所有学生
     * @Param []
     * @Return
     * @Author nanqiao
     * @Date 2025/6/14  15:05
     */
    @GetMapping("getAllStudents")
    public SaResult getAllStudents() {
        QueryWrapper<AllUser> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", 3);
        return SaResult.ok().setData(allUserMapper.selectList(wrapper));
    }

    /**
     * @Description 软删除用户
     * @param id 用户ID
     * @return 操作结果
     * @Author pml
     * @Date 2025/6/15 10:00
     */
    @DeleteMapping("/softDelete/{id}")
    public SaResult softDelete(@PathVariable Integer id) {
        // 调用服务层软删除方法，而非直接删除数据库记录
        // 软删除通过更新is_delete字段为1实现，保留数据用于审计和恢复
        return SaResult.ok().setData(allUserService.softDeleteById(id));
    }
    /**
     * 短信登录，查询电话号码是否存在，存在就发送验证码，不存在就返回提示
     */
    @GetMapping("/textMessageLogin")
    public SaResult textMessageLogin(@RequestParam String contact){
        //查电话号码是否存在
        AllUser user =allUserService.findByPhoneNumber(contact);
        if (user != null){
            //发送验证码
            ResponseData<String> stringResponseData = smsController.sendCode(contact);
            return SaResult.ok(stringResponseData.getData());
        }else {
            return SaResult.error("手机号不存在");
        }
    }
}
